//
//  FZSendBlogController.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/4/5.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit
import SVProgressHUD
class FZSendBlogController: UIViewController,UITextViewDelegate {

    fileprivate lazy var sendBlogBtn : UIButton = {
    
      let btn = UIButton()
      btn.setBackgroundImage(UIImage(named : "common_button_orange"), for: .normal)
      btn.setBackgroundImage(UIImage(named : "common_button_orange_highlighted"), for: .highlighted)
      btn.setBackgroundImage(UIImage(named : "common_button_white_disable"), for: .disabled)
      btn.setTitle("发送", for: .normal)
      btn.setTitleColor(UIColor.lightGray, for: .disabled)
      btn.setTitleColor(UIColor.white, for: .normal)
      btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
      btn.bounds.size = CGSize(width: 45, height: 35)
      btn.addTarget(self, action: #selector(sendBlogActions), for: .touchUpInside)
      return btn
    }()
    
    fileprivate lazy var customInputView : FZEmotionView = {
       let emotionView = FZEmotionView()
       emotionView.bounds.size = CGSize(width: self.blogTextView.bounds.width, height: emotionViewHeight)
       return emotionView
    }()
    
    fileprivate lazy var pictureView : FZPicsCollectionView = FZPicsCollectionView()
    
    fileprivate lazy var toolBarView : FZSendBlogToolBar = {
       let toolBar = FZSendBlogToolBar()
       
    
       return toolBar
    }()
    fileprivate lazy var blogTextView : FZBlogTextView = {
        let textView = FZBlogTextView()
        textView.textFont = 20
        
        return textView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
      
        setNavUI()
        setupUI()
    }
    
    fileprivate func setupUI() {
        
    NotificationCenter.default.addObserver(self, selector: #selector(getEmotionBtnModel(noti:)), name: NSNotification.Name(clickEmotionToTextViewNoti), object: nil)
 
       view.addSubview(blogTextView)
       view.addSubview(pictureView)
       view.addSubview(toolBarView)
       toolBarView.snp.makeConstraints { (make) in
                make.left.bottom.right.equalTo(self.view)
                make.height.equalTo(35)
        
        }
        
       blogTextView.delegate = self
       blogTextView.snp.makeConstraints { (make) in
          make.top.left.right.equalTo(self.view)
          make.bottom.equalTo(toolBarView.snp.top)
        }
       pictureView.snp.makeConstraints({ (make) in
          make.top.equalTo(self.view).offset(150)
          make.left.equalTo(self.view).offset(10)
          make.right.equalTo(self.view).offset(-10)
          make.height.equalTo(356)
        
       })
        pictureView.cameraClosure = { [weak self] in
            self?.openCamera()
        }
        
        toolBarView.buttonClosure = { [weak self] (buttonType : composeButtonType)->() in
        
            switch buttonType {
            case .camera:
                print("相机")
                self?.openCamera()
            case .mention:
                print("@谁谁谁")
            case .trend:
                print("#号")
            case .emoticon:
               self?.clickEmotionAction()
                print("表情")
            case .add:
                print("加号")
           
         }
       }
       blogTextView.placeHodlerString = "亲,请输入文字"
       blogTextView.alwaysBounceVertical = true
        
     //监听键盘
     NotificationCenter.default.addObserver(self, selector: #selector(keyBoardAction(noti:)), name: .UIKeyboardWillChangeFrame, object: nil)
        
 
      }
    @objc private func getEmotionBtnModel(noti : NSNotification) {
        
        let model = (noti.object) as! FZEmotionModel
        
        self.blogTextView.insertEmotion(emotion: model)
        
        FZEmotionViewModel.sharedEmotion.saveRecentEmotionArray(emotion: model)
        
        self.customInputView.reloadRecentCollection()
        
    }
    

        
   }

extension FZSendBlogController {
    
    func clickEmotionAction() {
        
        if blogTextView.inputView == nil {
            //由系统键盘进入表情键盘
            blogTextView.inputView = customInputView
            toolBarView.changeKeyBoardPattern(isEmotion: true)
            
        }else{
            toolBarView.changeKeyBoardPattern(isEmotion: false)
            //由表情键盘进入系统键盘
            blogTextView.inputView = nil
            
        }
        
        blogTextView.becomeFirstResponder()
        blogTextView.reloadInputViews()
    }

    fileprivate func scaleImageAction(img : UIImage)-> UIImage? {
        
        let scaleWidth : CGFloat = 200
        
        let scaleHeight : CGFloat = (scaleWidth / img.size.width) * img.size.height
        
        UIGraphicsBeginImageContext(CGSize(width: scaleWidth, height: scaleHeight))
        
        img.draw(in: CGRect(x: 0, y: 0, width: scaleWidth, height: scaleHeight))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image
    }
    
    @objc fileprivate func sendBlogActions() {
        
        let blog = blogTextView.emotionText
        
        let accessToken = FZUserViewModel.sharedUser.useraccount?.access_token
        
        let homeViewModel = FZHomeViewModel()
        
        var picsArr = [UIImage]()
        
        for picture in pictureView.imageArr{
            
            let picImg = scaleImageAction(img: picture)
            
            picsArr.append(picImg!)
        }
        
        
        if let access = accessToken{
            
            if pictureView.imageArr.count > 0 {
                
                //                let img = pictureView.imageArr.first
                
                homeViewModel.sendBlogAction(accessToken: access, status: blog, pics: picsArr, callBack: { (isSuccess) in
                    
                    if isSuccess {
                        SVProgressHUD.showSuccess(withStatus: "发布成功")
                        self.dismissVC()
                    }
                })
            }else{
                
                homeViewModel.sendBlogAction(accessToken: access, status: blog) { (isSuccess) in
                    if isSuccess {
                        SVProgressHUD.showSuccess(withStatus: "发布成功")
                        self.dismissVC()
                    }
                    
                }
                
            }
            
        }
    }

}
extension FZSendBlogController {
    
    
    @objc fileprivate func keyBoardAction(noti: NSNotification) {
        
        let keyBoardFrame = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as! CGRect
        
        let toolBarHeight : CGFloat = screenHeight - keyBoardFrame.origin.y
        if #available(iOS 9.0, *) {
            self.toolBarView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.view).offset(-toolBarHeight)
            }
        }
   }

}
extension FZSendBlogController : UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    
    //开启相机
    func openCamera() {
        
      let imageGallery = UIImagePickerController()
        imageGallery.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imageGallery.sourceType = .camera
        }
        
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            imageGallery.sourceType = .photoLibrary
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            //前置摄像头
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            //后置摄像头
        }
        
        self.present(imageGallery, animated: true, completion: nil)
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        /*
         ["UIImagePickerControllerMediaType": public.image, "UIImagePickerControllerReferenceURL": assets-library://asset/asset.JPG?id=106E99A1-4F6A-45A2-B320-B0AD4A8E8473&ext=JPG, "UIImagePickerControllerOriginalImage": <UIImage: 0x600000289f10> size {4288, 2848} orientation 0 scale 1.000000]
         */
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        pictureView.addImageToArr(picImg: image)
        picker.dismiss(animated: true, completion: nil)
    }
    
    
    
        fileprivate func setNavUI() {
            
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, selector:#selector(dismissVC) )
            navigationItem.titleView = customTitleView()
            navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.sendBlogBtn)
            navigationItem.rightBarButtonItem?.isEnabled = false
        }
        
        fileprivate func customTitleView() -> UILabel? {
            
            let lab = UILabel()
            lab.font = UIFont.systemFont(ofSize: 14)
            lab.textColor = UIColor.darkGray
            
            let name = FZUserViewModel.sharedUser.useraccount?.name
            if let userName = name  {
                
                let message = "发微博\n" + userName
                let nameRange = (message as NSString).range(of:userName)
                
                let attribute : NSMutableAttributedString = NSMutableAttributedString(string: message)
                
                attribute.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName : UIColor.orange], range: nameRange)
                
                lab.attributedText = attribute
                lab.numberOfLines = 0
                lab.sizeToFit()
                lab.textAlignment = .center
            }
            return lab
            
        }
        
        @objc fileprivate func dismissVC() {
            dismiss(animated: true, completion: nil)
            self.view.endEditing(true)
        }
        
        func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
            self.view.endEditing(true)
        }

        


}











